<?php

// **************************************************************
// | Name: 星空框架  产品服务
// **************************************************************
// | Version: V5.0
// **************************************************************
// | Author: xkyinzhe <zhonghuaxinxing@sina.cn>
// **************************************************************
// | City: 青岛
// **************************************************************
// | Time: 2021-04-26 17:02
// **************************************************************
declare(strict_types=1);

namespace app\common\services;

use app\common\model\GoodsParameters as GoodsParametersModel;
use app\common\model\GoodsPic as GoodsPicModel;
use app\common\model\SpecPrice as SpecPriceModel;
use app\common\model\GoodsSpec as GoodsSpecModel;
use app\common\model\Goods as GoodsModel;
use app\common\model\Car as CarModel;
use app\common\model\GoodsSpecValue as GoodsSpecValueModel;
use think\facade\Session;

/**
 * @xk 产品服务
 */
class GoodsServices
{
    /**
     * @xk 产品保存后 更新规格价格体系
     *
     * @method updateSpecPrice
     *
     * @param [type] $goods_id [description]
     * @param [type] $sku_data [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-04-26T17:05:50+080
     */
    public static function updateSpecPrice($goods_id, $sku_data = [], $is_onsell = 0)
    {
        $specPriceModel = new SpecPriceModel();
        $condition = [];
        $condition[] = ['goods_id', '=', $goods_id];

        $create_data = [];
        $delete_data = [];
        $sku_key_arr = [];
        $spec_price_list = $specPriceModel->where($condition)->column('sku_key', 'spec_price_id');
        if ($sku_data) {
            foreach ($sku_data as $key => $value) {
                $data = [];
                $data['goods_id'] = $goods_id;
                $data['sku_key'] = (string)$key;
                $data['picurl'] = $value['picurl'];
                $data['sku_value'] = $value['sku_value'];
                $data['selling_price'] = $value['selling_price'];
                // $data['market_price'] = $value['market_price'];
                // $data['market_price'] = $value['market_price'];
                $data['achievement_bili'] = $value['achievement_bili'];
                $data['bonus_price'] = $value['bonus_price'];
                $data['next_bonus_price'] = $value['next_bonus_price'];
                // $data['real_num'] = $value['real_num'];
                // $data['weight'] = $value['weight'];
                // $data['stock'] = $value['stock'];
                $data['sku'] = $value['sku'];
                $data['is_onsell'] = $is_onsell;
                $create_data[] = $data;
                if (in_array($key, $spec_price_list)) {
                    $spec_price_res = $specPriceModel
                                      ->where([['goods_id', '=', $goods_id], ['sku_key', '=', $key]])
                                      ->save($data);
                } else {
                    $spec_price_res = $specPriceModel->create($data);
                }
            }
            $sku_key_arr = array_keys($sku_data);
        }
        // 删除不需要的规格价格体系
        if ($spec_price_list) {
            foreach ($spec_price_list as $key => $value) {
                if (!in_array($value, $sku_key_arr)) {
                    $delete_data[] = $key;
                }
            }
            if ($delete_data) {
                $spec_delete_res = $specPriceModel->destroy($delete_data);
            }
        }

        return true;
    }
    /**
     * @xk 执行产品规格模型创建 以及产品规格价格体系的建立
     *
     * @method updateSpec
     * @param  [type]     $goods_id                  [description]
     * @param  array      $spec_list                 [description]
     * @param  array      $sku_data                  [description]
     * @return [type]     [description]
     * @Time   2021-08-23
     * @City   青岛
     * @Author xkyinzhe   <zhonghuaxinxing@sina.cn>
     */
    public static function updateSpec($goods_id, $goods_attr_id, $spec_list = [], $sku_data = [])
    {
        try {
            $goodsSpecModel = new GoodsSpecModel();
            $goodsSpecValueModel = new GoodsSpecValueModel();
            // 查询对应产品 对应属性 是否已经存在对应的规格价格体系
            $goods_spec_arr = $goodsSpecModel
                          ->where([['goods_id','=',$goods_id],['goods_attr_id','=',$goods_attr_id]])
                          ->column('goods_spec_id');
            $has_goods_spec_arr = [];
            // 如果存在 则获取全部的规格 选项
            //
            Session::set('sku_data', $sku_data);
            if($spec_list){
              foreach ($spec_list as $key => $value) {
                if (!isset($value['spec_value'])) {
                  continue;
                }
                $goods_spec_data = [];
                $goods_spec_data['spec_name'] = $value['name'];
                $goods_spec_data['spec_value_str'] = implode(',', $value['spec_value']);
                $goods_spec_data['goods_id'] = $goods_id;
                $goods_spec_data['goods_attr_id'] = $goods_attr_id;
                // 判断当前属于新增还是修改
                if ($key > 0) {
                  $res = $goodsSpecModel
                  ->find($key)
                  ->save($goods_spec_data);
                  $goods_spec_id = $key;
                } else {
                  $res = $goodsSpecModel
                  ->create($goods_spec_data);
                  $goods_spec_id = $res->goods_spec_id;
                }
                $has_goods_spec_arr[] = $goods_spec_id;
                $has_goods_spec_value_arr = $goodsSpecValueModel
                ->where([['goods_spec_id','=',$goods_spec_id]])
                ->column('goods_spec_value_id');
                $goods_spec_value_arr = [];
                foreach ($value['spec_key'] as $k => $val) {
                  $goods_spec_value_data = [];
                  $goods_spec_value_data['goods_spec_id'] = $goods_spec_id;
                  $goods_spec_value_data['goods_id'] = $goods_id;
                  $goods_spec_value_data['spec_value'] = $value['spec_value'][$k];
                  if ($value['spec_value_key'][$k] > 0) {
                    // 之前的数据
                    $res = $goodsSpecValueModel
                    ->find($value['spec_value_key'][$k])
                    ->save($goods_spec_value_data);
                    $goods_spec_value_id = $value['spec_value_key'][$k];
                  } else {
                    // 新增的数据
                    $res = $goodsSpecValueModel->create($goods_spec_value_data);
                    $goods_spec_value_id = $res->goods_spec_value_id;
                  }
                  $goods_spec_value_arr[] = $goods_spec_value_id;
                  $new_data = [];
                  if (Session::get('sku_data')) {
                    foreach (Session::get('sku_data') as $kx => $vlue) {
                      if (stristr((string)$kx, '_') != false) {
                        $key_arr = explode('_', $kx);
                        if (in_array($val, $key_arr)) {
                          $i = array_search($val, $key_arr);
                          $key_arr[$i] = $goods_spec_value_id;
                          sort($key_arr);
                          $kxx = implode('_', $key_arr);
                          $new_data[$kxx] = $vlue;
                        } else {
                          $new_data[$kx] = $vlue;
                        }
                      } else {
                        if ($val == $kx) {
                          $keyx = (string)$goods_spec_value_id;
                          $new_data[(string)$keyx] = $vlue;
                        } else {
                          $new_data[$kx] = $vlue;
                        }
                      }
                    }
                    Session::set('sku_data', $new_data);
                  }
                }
                $destroy_spec_values_data = [];
                foreach ($has_goods_spec_value_arr as $km => $vm) {
                  if (!in_array($vm, $goods_spec_value_arr)) {
                    $destroy_spec_values_data[] = $vm;
                  }
                }
                if ($destroy_spec_values_data) {
                  $spec_value_res = $goodsSpecValueModel->destroy($destroy_spec_values_data);
                }
              }
            }
            // 清理不需要的规格选项
            $destroy_values_data = [];
            foreach ($goods_spec_arr as $key => $value) {
                if (!in_array($value, $has_goods_spec_arr)) {
                    $destroy_values_data[] = $value;
                }
            }
            if ($destroy_values_data) {
                $spec_destroy_res = $goodsSpecModel->destroy($destroy_values_data);
            }
            self::updateSpecPrice($goods_id, Session::get('sku_data'), 0);
        } catch (\Exception $e) {
            throw new \think\Exception($e->getMessage(), 404);
        }
    }

    /**
     * @xk 产品保存后 更新产品参数体系
     *
     * @method updateGoodsParameters
     *
     * @param [type] $goods_id        [description]
     * @param [type] $sku_key_data    [description]
     * @param [type] $attr_value_data [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-04-27T08:53:18+080
     */
    public static function updateGoodsParameters($goods_id, $sku_key_data, $sku_values_data)
    {
        $goodsParametersModel = new GoodsParametersModel();
        $condition = [];
        $condition[] = ['goods_id', '=', $goods_id];
        $goods_parameters_delete_res = $goodsParametersModel->destroy(function ($query) use ($condition) {
            $query->where($condition);
        });
        $create_data = [];
        if ($sku_key_data) {
            foreach ($sku_key_data as $key => $value) {
                $create_data[] = [
            'goods_id' => $goods_id,
            'attr_key' => $value,
            'attr_value' => $sku_values_data[$key],
          ];
            }
        }
        $goods_parameters_res = $goodsParametersModel->saveAll($create_data);
    }

    /**
     * @xk 产品图片更新
     *
     * @method updateGoodsPic
     *
     * @param [type] $goods_id [description]
     * @param [type] $pic_arr  [description]
     * @param [type] $pic_name [description]
     * @param [type] $pic_size [description]
     *
     * @return [type] [description]
     * @Author xkyinzhe                <zhonghuaxinxing@sina.cn>
     * @Time   2021-04-27T11:35:06+080
     */
    public static function updateGoodsPic($goods_id, $pic_arr, $pic_name, $pic_size)
    {
        $goodsPicModel = new GoodsPicModel();
        $condition = [];
        $condition[] = ['goods_id', '=', $goods_id];
        $goods_pic_del_res = $goodsPicModel->destroy(function ($query) use ($condition) {
            $query->where($condition);
        });
        $create_data = [];
        if ($pic_arr) {
            foreach ($pic_arr as $key => $value) {
                $create_data[] = [
                'goods_id' => $goods_id,
                'picurl' => $value,
                'picname' => $pic_name[$key],
                'picsize' => $pic_size[$key],
              ];
            }
        }
        $goods_pic_res = $goodsPicModel->saveAll($create_data);
    }
    /**
     * @xk 同步更新购物车数据
     * @method                                      updateCar
     * @param                                       int $goods_id  [description]
     * @param                                       array $spec_list  [description]
     * @return                                      [type] [description]
     * @Version：V5.0
     * @Author：xkyinzhe                             <zhonghuaxinxing@sina.cn>
     * @City：                                       青岛
     * @Time：2022-02-17Tfalse16:false45:false58+080
     */
    public static function updateCar($goods_id=0){
      $carModel = new CarModel();
      $goodsModel = new GoodsModel();
      $specPriceModel = new SpecPriceModel();
      // 获取产品信息
      $goods_info = $goodsModel->field('`goods_name`,`picurl`,`store_id`,`selling_price`,`vip_buy_bili`,`bonus_price`,`next_bonus_price`,`bonus_type`,`achievement_bili`')->find($goods_id);
      if(!$goods_info){
        throw new \think\Exception("同步产品不存在", 404);
      }
      $attr_count = $specPriceModel->where([['goods_id','=',$goods_id]])->count(); // 判断是否存在规格
      // 获取购物车中产品列表
      $car_list = $carModel
                  ->where([['goods_id','=',$goods_id],['status','=',0]])
                  ->field('`car_id`,`spec_key`,`spec_value`,`spec_price_id`,`is_buy`')
                  ->select()
                  ->toArray();
      if($car_list){
        foreach ($car_list as $key => $value) {
          $car_data = [];
          $car_data['goods_name'] = $goods_info['goods_name'];
          $car_data['selling_price'] = $goods_info['selling_price'];
          $car_data['goods_price'] = $goods_info['selling_price'];
          if($value['is_buy'] == 1){
            $car_data['goods_price'] = (float)$goods_info['selling_price']*(float)$goods_info['vip_buy_bili'];
          }
          $car_data['vip_buy_bili'] = $goods_info['vip_buy_bili'];
          $car_data['bonus_price'] = $goods_info['bonus_price'];
          $car_data['next_bonus_price'] = $goods_info['next_bonus_price'];
          $car_data['bonus_type'] = $goods_info['bonus_type'];
          $car_data['achievement_bili'] = $goods_info['achievement_bili'];
          $car_data['goods_name'] = $goods_info['goods_name'];
          // 查询 规格信息
          $spec_info = $specPriceModel
          ->where([['sku_key','=',$value['spec_key']],['goods_id','=',$goods_id]])
          ->field('`spec_price_id`,`selling_price`,`achievement_bili`,`bonus_price`,`next_bonus_price`,`picurl`')
          ->find();
          $spec_info = $spec_info?$spec_info->toArray():[];
          if(($attr_count > 0 && !$spec_info) || $goods_info['is_onsell'] == 1) {
            // 存在规格  但是没有查询到对应的规格数据
            $carModel->destroy($value['car_id']); // 删除购物车数据
            continue;
          }
          if($attr_count > 0 && $spec_info){
            // 存在规格 并且查询到了数据
            $car_data['selling_price'] = $spec_info['selling_price'];
            $car_data['goods_price'] = $spec_info['selling_price'];
            if($value['is_buy'] == 1){
              $car_data['goods_price'] = (float)$spec_info['selling_price']*(float)$goods_info['vip_buy_bili'];
            }
            $car_data['bonus_price'] = $spec_info['bonus_price'];
            $car_data['next_bonus_price'] = $spec_info['next_bonus_price'];
            $car_data['achievement_bili'] = $spec_info['achievement_bili'];
            $car_data['goods_pic'] = $spec_info['picurl'];
            $car_data['spec_price_id'] = $spec_info['spec_price_id'];
          }
          $carModel->find($value['car_id'])->save($car_data);
        }
      }


    }
}
